<template>
	<view class="login">
		<view class="title">
			西瓜记账
		</view>
		<view class="content">
			<view class="input">
				<uni-icons type="person" size="30"></uni-icons>
				<input type="number"  maxlength="11"
				 v-model="formData.username" placeholder="请输入手机号" name="" id="" value="" />
			</view>
			<view class="input">
				<uni-icons type="locked" size="30"></uni-icons>
				<input type="password" v-model="formData.password" placeholder="请输入密码" name="" id="" value="" />
			</view>
			<view class="register" @click="toRegister">
				快速注册
			</view>
			<button type="primary" @click="getLogin">登录</button>
		</view>
	</view>
</template>

<script>
	// 从 vuex 中按需导出 mapState 辅助方法
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				formData: {
					username: "",
					password: ""
				},
				isLoading: false
			};
		},
		onLoad() {
			if(this.userInfo.username){
				console.log("存在缓存用户数据");
				// 跳转页面
				uni.switchTab({
					url: '/pages/my/my'
				});
			}
		},
		computed: {
			...mapState('m_user', ['userInfo']),
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo']),
			toRegister() {
				console.log("点击了快速注册");
				uni.navigateTo({
					url: '../register/register'
				});
			},
			// 用户登录
			async getLogin() {
				console.log("账号和密码", this.formData);
				const {
					data: res
				} = await uni.$http.post("/user/loginUser",
					this.formData
				)
				console.log("查询用户是否存在", res);
				if (res.code !== 0) return uni.$showMsg("登录失败,请检查账号或密码")
				uni.$showMsg("登录成功!")
				// 将用户信息存到vuex中
				this.updateUserInfo(res.data)
				
				// 跳转页面
				uni.switchTab({
					url: '/pages/my/my'
				});

			},
		}
	}
</script>

<style lang="scss">
	.login {
		background-color: #38A678;
		height: 100vh;
		padding: 50px 10px 0 10px;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;

		.title {
			font-size: 25px;
			color: #fff;
			font-weight: bold;
		}

		.content {
			margin-top: 10px;
			background-color: #fff;
			border-radius: 10px;
			box-sizing: border-box;
			padding: 10px;
			height: 240px;
			display: flex;
			flex-direction: column;
			justify-content: space-around;

			.input {
				display: flex;
				align-items: center;
				border-bottom: 1px solid #999;
			}

			.register {
				display: flex;
				justify-content: flex-end;
				color: #999;
			}

			button {
				width: 100%;
			}
		}
	}
</style>
